package servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * servlet
 * 测试请求参数乱码
 *
 * 2018/5/13-21:31
 * 2018
 * Created by wuqiang on 2018/5/13.
 */
public class RequestDemo1 extends HttpServlet {
    /**
     * 接收表单参数
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = req.getParameter("username");
        System.out.println(username);//这样中文会乱码
        resp.getWriter().write(username);//而反写回去，则不会乱码

        String characterEncoding = req.getCharacterEncoding();
        System.out.println(characterEncoding);
        req.setCharacterEncoding("UTF-8");
        String characterEncoding2 = req.getCharacterEncoding();
        System.out.println(characterEncoding2);
        String user=req.getParameter("username");
        System.out.println(user);
    }

    @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        System.out.println(username);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write(username);
    }
}
